package com.imooc.security.filter;

import com.imooc.security.user.UserInfo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.swing.text.html.Option;
import java.util.Optional;

/**
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/5/1 18:10
 * @Version 1.0
 */
@Configuration
@EnableJpaAuditing //JPA审计的总开关
public class SecurityConfig implements WebMvcConfigurer {

    @Autowired
    private AuditLogInterceptor auditLogInterceptor;

    @Autowired
    private AclInterceptor aclInterceptor;

    /**
     * @Description TODO 将审计拦截器添加到mvc容器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(auditLogInterceptor);
        registry.addInterceptor(aclInterceptor);
    }

    @Bean
    public AuditorAware<String> auditorAware(){
        return new AuditorAware<String>() {
            @Override
            public Optional<String> getCurrentAuditor() {
                // 从session中拿到用户信息
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                UserInfo info = (UserInfo) servletRequestAttributes.getRequest().getSession().getAttribute("user");
                String username = null;
                if (info != null){
                    username = info.getUsername();
                }
//                return Optional.of("wsp");
                return Optional.ofNullable(username);
            }
        };
    }
}
